package com.karaku.karaku_collector.keepalive;

import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.IntDef;
import android.support.v4.app.NotificationCompat;

import com.karaku.karaku_collector.App;
import com.karaku.karaku_collector.R;
import com.karaku.karaku_collector.activity.MainActivity;
import com.karaku.karaku_collector.util.LogUtil;
import com.karaku.karaku_collector.util.ProcessUtil;

public class KeepAliveService extends Service {

    private Handler handler = new Handler();
    private Runnable heartbeatRunnable = new Runnable() {
        @Override
        public void run() {
            LogUtil.d("STATE", "heartbeatRunnable");
            if (ProcessUtil.hasMainProcess()) {
                Intent i = new Intent("com.karaku.karaku_collector.KEEP_ALIVE");
                sendBroadcast(i);
            } else {
                Intent i = new Intent(App.getInstance(), MainActivity.class);
                i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(i);
            }
            beginHeartbeat();
        }
    };

    public KeepAliveService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Intent i = new Intent(getApplicationContext(), MainActivity.class);
        PendingIntent pi = PendingIntent.getActivity(getApplicationContext(),  0, i, 0);
        NotificationCompat.Builder b = new NotificationCompat.Builder(this).setSmallIcon(R.mipmap.ic_launcher).setTicker("Karaku采集端").setWhen(System.currentTimeMillis()).setContentTitle("Karaku采集端")
                .setContentIntent(pi);
        Notification n = b.build();
        startForeground(1, n);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        LogUtil.d("STATE", "onStartCommand");
        boolean enable = intent.getBooleanExtra("enable_heartbeat", false);
        handler.removeCallbacksAndMessages(null);
        if (enable) {
            LogUtil.d("STATE", "onStartCommand1");
            beginHeartbeat();
        }
        LogUtil.d("STATE", "onStartCommand2");
        return super.onStartCommand(intent, flags, startId);
    }

    public void beginHeartbeat() {
        LogUtil.d("STATE", "beginHeartbeat");
        handler.postDelayed(heartbeatRunnable, 5000);
    }

}
